package com.gzq.singleton.practice0;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class MethodLocked implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public static void main(String[] args)
			throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException,
			IllegalArgumentException, InvocationTargetException, IOException, ClassNotFoundException {
		MethodLocked singleton1 = MethodLocked.getSingleton();
		MethodLocked singleton2 = MethodLocked.getSingleton();
		System.out.println(singleton1);
		System.out.println(singleton2);

		// 反射
		Constructor<MethodLocked> constructor = MethodLocked.class.getDeclaredConstructor();
		constructor.setAccessible(true);
		MethodLocked newInstance = constructor.newInstance();
		System.out.println(newInstance);

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ObjectOutputStream oos = new ObjectOutputStream(baos);
		oos.writeObject(singleton1);

		byte[] byteArray = baos.toByteArray();

		InputStream inputStream = new ByteArrayInputStream(byteArray);
		ObjectInputStream ois = new ObjectInputStream(inputStream);
		Object readObject = ois.readObject();
		System.out.println(readObject);

	}

	private static MethodLocked singleton;

	private MethodLocked() {

	}

	public static synchronized MethodLocked getSingleton() {
		if (singleton == null) {
			singleton = new MethodLocked();
		}
		return singleton;
	}

}
